package com.uyaer.engine.display
{
	import com.uyaer.engine.Const;
	import com.uyaer.engine.Globle;
	import com.uyaer.engine.core.Bean;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	public class Icon extends Sprite
	{
		private var loader:Loader;
		public var bm:Bitmap;
		public var animMc:MovieClip; 
		public var bean:Bean;
		public var size:int;
		private var url:String;
		private var isAnim:Boolean;
		public var isCanHover:Boolean = true;
		public var hoverId:int;
		public var hoverOverHandler:Function;
		public var hoverOutHandler:Function;
		public function Icon(bean:Bean , size:int = 0 ,url:String = "" , isAnim:Boolean = false)
		{
			this.bean = bean;
			this.size = size;
			this.url = url;
			this.isAnim = isAnim;
			
			this.mouseChildren = false;
			
			bm = new Bitmap();
			
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, _loadOver);
			loader.load(new URLRequest(comurl()));
			
			this.addEventListener(MouseEvent.ROLL_OVER , _onOver);
			this.addEventListener(MouseEvent.ROLL_OUT, _onOut);
		}
		
		/**
		 *创建完整路径 
		 * @return 
		 * 
		 */		
		private function comurl():String
		{
			if(!url){
				url = bean.resName;
				if(size != 0){
					url += "_"+size + "_" + size;
				}
				if(isAnim){
					url += ".swf";
				}else{
					if(bean){
						url += "."+bean.resType;
					}else{
						url += "png";
					}
				}
			}
			return url;
		}
		
		private function _loadOver(e:Event):void{
			if(!isAnim){
				var bmd:BitmapData = (loader.contentLoaderInfo.content as Bitmap).bitmapData.clone();
				bm.bitmapData = bmd;
				addChildAt(bm,0);
			}else{
				animMc = loader.contentLoaderInfo.content as MovieClip;
				addChildAt(animMc,0);
			}
			loader.unload();
		}
		
		private function _onOver(e:MouseEvent):void{
			isCanHover = true;
			hoverId = setTimeout(_hoverOver,300);
		}
		
		private function _hoverOver():void{
			clearTimeout(hoverId);
			if(isCanHover){
				hoverOverHandler && hoverOverHandler();
			}
		}
		
		private function _onOut(e:MouseEvent):void{
			if(hoverId){
				clearTimeout(hoverId);
			}else{
				if(isCanHover){
					hoverOutHandler && hoverOutHandler();
				}
			}
		}
		
		public function destory():void{
			if(bm){
				bm.bitmapData.dispose();
				if(bm.parent){
					bm.parent.removeChild(bm);
				}
			}else if(animMc){
				animMc.gotoAndStop(1);
				if(animMc.parent){
					animMc.parent.removeChild(animMc);
				}
			}
		}
	}
}